package com.ruoyi.factory.costControl.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.factory.common.utils.IdGen;
import com.ruoyi.factory.costControl.domain.*;
import com.ruoyi.factory.costControl.mapper.*;
import com.ruoyi.factory.costControl.service.CostHandleService;
import com.ruoyi.factory.qylock.utils.OkHttpUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CostHandleServiceImpl  implements CostHandleService {
    protected final Logger logger = LoggerFactory.getLogger(CostHandleServiceImpl.class);

    @Value("${feikong.url}")
    private String sendfkurl;
    @Value("${feikong.compid}")
    private String compid;
    @Value("${feikong.account}")
    private String account;
    @Value("${feikong.responseType}")
    private String responseType;
    @Value("${feikong.signType}")
    private String signType;
    @Value("${feikong.key}")
    private String key;
    @Value("${feikong.ip}")
    private String ip;
    @Autowired
    private BudgetInfoMapper budgetInfoMapper;
    @Autowired
    private StaffInfoMapper staffInfoMapper;
    @Autowired
    private PersonBankInfoMapper personBankInfoMapper;
    @Autowired
    private CustomerInfoMapper customerInfoMapper;
    @Autowired
    private ProjectInfoMapper projectInfoMapper;
    @Autowired
    private FundplanInfoMapper fundplanInfoMapper;
    @Autowired
    private CurrtypeInfoMapper currtypeInfoMapper;
    @Autowired
    private TaxcodeInfoMapper taxcodeInfoMapper;
    @Autowired
    private RateInfoMapper rateInfoMapper;
    @Autowired
    private CustbankInfoMapper custbankInfoMapper;
    @Autowired
    private SupplierInfoMapper supplierInfoMapper;
    @Autowired
    private OrgBankInfoMapper orgBankInfoMapper;
    @Autowired
    private PaybillMapper paybillMapper;
    @Autowired
    private PayConMapper payConMapper;
    @Autowired
    private AccasoaInfoMapper accasoaInfoMapper;


    /**
     * 获取员工信息
     * @return
     */
    @Override
    public AjaxResult getStaffInfo(String req, HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        logger.info("获取员工信息请求者地址: "+remoteAddr);
        if(!ip.contains(remoteAddr)) return new AjaxResult(HttpStatus.ERROR,"error","请联系管理员设置访问白名单");
        JSONObject jsonObject = JSONObject.fromObject(req);
        StaffInfo staffInfo = JSON.parseObject(req, StaffInfo.class);
        List<StaffInfo> staffInfos = staffInfoMapper.selectStaffInfo(staffInfo);
        return new AjaxResult(HttpStatus.SUCCESS,"success",staffInfos);
    }

    /**
     * 获取银行卡信息
     * @param req
     * @param request
     * @return
     */
    @Override
    public AjaxResult getPersonBankInfo(String req, HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        logger.info("获取银行卡信息请求者地址: "+remoteAddr);
        if(!ip.contains(remoteAddr)) return new AjaxResult(HttpStatus.ERROR,"error","请联系管理员设置访问白名单");
        JSONObject jsonObject = JSONObject.fromObject(req);
        PersonBankInfo personBankInfo = JSON.parseObject(req, PersonBankInfo.class);
        List<PersonBankInfo> personBankInfos = personBankInfoMapper.selectPersonBankInfo(personBankInfo);
        return new AjaxResult(HttpStatus.SUCCESS,"success",personBankInfos);
    }

    /**
     * 获取客户信息
     * @param req
     * @param request
     * @return
     */
    @Override
    public AjaxResult getCustomerInfo(String req, HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        logger.info("获取客户信息请求者地址: "+remoteAddr);
        if(!ip.contains(remoteAddr)) return new AjaxResult(HttpStatus.ERROR,"error","请联系管理员设置访问白名单");
        JSONObject jsonObject = JSONObject.fromObject(req);
        CustomerInfo customerInfo = JSON.parseObject(req, CustomerInfo.class);
        List<CustomerInfo> customerInfos = customerInfoMapper.selectCustomerInfo(customerInfo);
        Map<String,String> hmap = new HashMap<>();
        Map<String,String> hmap2 = new HashMap<>();
        for (CustomerInfo info : customerInfos) {
            String name = info.getName();
            String pk_supplier = info.getPk_customer();
            String s = hmap.get(pk_supplier);
            if(StringUtils.isNotBlank(s)){
                hmap2.put(pk_supplier,name);
            }else{
                hmap.put(pk_supplier,name);
            }
        }
        System.out.println("BU重复"+hmap.toString());
        System.out.println("重复"+hmap2.toString());
        return new AjaxResult(HttpStatus.SUCCESS,"success",customerInfos);
    }

    /**
     * 获取项目信息
     * @param req
     * @param request
     * @return
     */
    @Override
    public AjaxResult getProjectInfo(String req, HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        logger.info("获取项目信息请求者地址: "+remoteAddr);
        if(!ip.contains(remoteAddr)) return new AjaxResult(HttpStatus.ERROR,"error","请联系管理员设置访问白名单");
        JSONObject jsonObject = JSONObject.fromObject(req);
        ProjectInfo projectInfo = JSON.parseObject(req, ProjectInfo.class);
        List<ProjectInfo> projectInfos = projectInfoMapper.selectProjectInfo(projectInfo);
        return new AjaxResult(HttpStatus.SUCCESS,"success",projectInfos);
    }

    /**
     * 获取资金取项目信息
     * @param req
     * @param request
     * @return
     */
    @Override
    public AjaxResult getFundplanInfo(String req, HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        logger.info("获取资金取项目信息请求者地址: "+remoteAddr);
        if(!ip.contains(remoteAddr)) return new AjaxResult(HttpStatus.ERROR,"error","请联系管理员设置访问白名单");
        JSONObject jsonObject = JSONObject.fromObject(req);
        FundplanInfo fundplanInfo = JSON.parseObject(req, FundplanInfo.class);
        List<FundplanInfo> fundplanInfos = fundplanInfoMapper.selectFundplanInfo(fundplanInfo);
        return new AjaxResult(HttpStatus.SUCCESS,"success",fundplanInfos);
    }

    /**
     * 获取币种信息
     * @param req
     * @param request
     * @return
     */
    @Override
    public AjaxResult getCurrtypeInfo(String req, HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        logger.info("获取币种信息请求者地址: "+remoteAddr);
        if(!ip.contains(remoteAddr)) return new AjaxResult(HttpStatus.ERROR,"error","请联系管理员设置访问白名单");
        JSONObject jsonObject = JSONObject.fromObject(req);
        CurrtypeInfo currtypeInfo = JSON.parseObject(req, CurrtypeInfo.class);
        List<CurrtypeInfo> currtypeInfos = currtypeInfoMapper.selectCurrtypeInfo(currtypeInfo);
        return new AjaxResult(HttpStatus.SUCCESS,"success",currtypeInfos);
    }

    /**
     * 增值税税码税率
     * @param req
     * @param request
     * @return
     */
    @Override
    public AjaxResult getTaxcodeInfo(String req, HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        logger.info("获取增值税税码税率信息请求者地址: "+remoteAddr);
        if(!ip.contains(remoteAddr)) return new AjaxResult(HttpStatus.ERROR,"error","请联系管理员设置访问白名单");
        JSONObject jsonObject = JSONObject.fromObject(req);
        TaxcodeInfo taxcodeInfo = JSON.parseObject(req, TaxcodeInfo.class);
        List<TaxcodeInfo> taxcodeInfos = taxcodeInfoMapper.selectTaxcodeInfo(taxcodeInfo);
        return new AjaxResult(HttpStatus.SUCCESS,"success", taxcodeInfos);
    }

    /**
     * 日汇率
     * @param req
     * @param request
     * @return
     */
    @Override
    public AjaxResult getCurrrateInfo(String req, HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        logger.info("获取日汇率信息请求者地址: "+remoteAddr);
        if(!ip.contains(remoteAddr)) return new AjaxResult(HttpStatus.ERROR,"error","请联系管理员设置访问白名单");
        JSONObject jsonObject = JSONObject.fromObject(req);
        RateInfo currrateInfo = JSON.parseObject(req, RateInfo.class);
        List<RateInfo> currrateInfos = rateInfoMapper.selectRateInfo(currrateInfo);
        return new AjaxResult(HttpStatus.SUCCESS,"success", currrateInfos);
    }

    /**
     * 供应商和客户银行信息
     * @param req
     * @param request
     * @return
     */
    @Override
    public AjaxResult getCustbankInfo(String req, HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();

        logger.info("获取供应商和客户银行信息请求者地址: "+remoteAddr);
        if(!ip.contains(remoteAddr)) return new AjaxResult(HttpStatus.ERROR,"error","请联系管理员设置访问白名单");
        JSONObject jsonObject = JSONObject.fromObject(req);
        CustbankInfo custbankInfo = JSON.parseObject(req, CustbankInfo.class);
        List<CustbankInfo> custbankInfos = custbankInfoMapper.selectCustbankInfo2(custbankInfo);
        return new AjaxResult(HttpStatus.SUCCESS,"success", custbankInfos);
    }

    /**
     * 供应商信息
     * @param req
     * @param request
     * @return
     */
    @Override
    public AjaxResult getSupplierInfo(String req, HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        logger.info("获取供应商信息请求者地址: "+remoteAddr);
        if(!ip.contains(remoteAddr)) return new AjaxResult(HttpStatus.ERROR,"error","请联系管理员设置访问白名单");
//        JSONObject jsonObject = JSONObject.fromObject(req);
        SupplierInfo supplierInfo = JSON.parseObject(req, SupplierInfo.class);
        List<SupplierInfo> supplierInfos = supplierInfoMapper.selectSupplierInfo(supplierInfo);

        return new AjaxResult(HttpStatus.SUCCESS,"success", supplierInfos);
    }

    /**
     * 供应商信息
     * @param req
     * @param request
     * @return
     */
    @Override
    public AjaxResult getOrgBankInfo(String req, HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        logger.info("组织银行账户信息请求者地址: "+remoteAddr);
        if(!ip.contains(remoteAddr)) return new AjaxResult(HttpStatus.ERROR,"error","请联系管理员设置访问白名单");
//        JSONObject jsonObject = JSONObject.fromObject(req);
        OrgBankInfo orgBankInfo = JSON.parseObject(req, OrgBankInfo.class);
        List<OrgBankInfo> orgBankInfos = orgBankInfoMapper.selectOrgBankInfo(orgBankInfo);
        return new AjaxResult(HttpStatus.SUCCESS,"success", orgBankInfos);
    }

    /**
     * 获取会计科目
     * @param req
     * @param request
     * @return
     */
    @Override
    public AjaxResult getAccasoa(String req, HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        logger.info("会计科目请求者地址: "+remoteAddr);
        if(!ip.contains(remoteAddr)) return new AjaxResult(HttpStatus.ERROR,"error","请联系管理员设置访问白名单");
//        JSONObject jsonObject = JSONObject.fromObject(req);
        AccasoaInfo accasoaInfo = JSON.parseObject(req, AccasoaInfo.class);
        List<AccasoaInfo> accasoaInfos = accasoaInfoMapper.selectAccasoaInfo(accasoaInfo);
        return new AjaxResult(HttpStatus.SUCCESS,"success", accasoaInfos);
    }

    /**
     * 推送预算信息到费控平台
     */
    @Override
    public void pushBudgetTofk(String year, String month){
        //查询当月erp所有预算数据
        //系统定时任务有值则使用定时任务的值,定时任务没有值则使用默认值,每天早上同步
        BudgetInfo params = new BudgetInfo();
        if(StringUtils.isNotEmpty(year) && StringUtils.isNotEmpty(month)){
            params.setYear(String.valueOf(year));
            Integer integer = Integer.valueOf(month);
            month = String.format("%02d", integer);
            params.setMonth(String.valueOf(month));
        }else{
            Calendar instance = Calendar.getInstance();
            int y = instance.get(Calendar.YEAR);
            int m = instance.get(Calendar.MONTH)+ 1;
            String fm = String.format("%02d", m);
            params.setYear(String.valueOf(y));
            params.setMonth(String.valueOf(fm));
        }
        //部门预算 月
        List<BudgetInfo> budgetInfos = budgetInfoMapper.selectBudgetInfo(params);
        handbudgetdate(budgetInfos,"部门月预算");
        //组织预算 月
        List<BudgetInfo> budgetInfos1 = budgetInfoMapper.selectBudgetInfoOrg(params);
        handbudgetdate(budgetInfos1,"组织月预算");
        //部门预算 月研发费用
        List<BudgetInfo> budgetInfosyf = budgetInfoMapper.selectBudgetInfoyf(params);
        handbudgetdate(budgetInfosyf,"部门月预算研发费用");
        //组织预算 月研发费用
//        List<BudgetInfo> budgetInfos1yf = budgetInfoMapper.selectBudgetInfoOrgyf(params);
//        handbudgetdate(budgetInfos1yf,"组织月预算研发费用");
        //年预算
//        BudgetInfo params2 = new BudgetInfo();
//        params2.setYear(params.getYear());
//        params2.setMonth("~");
//        //部门预算 年
//        List<BudgetInfo> budgetInfos2 = budgetInfoMapper.selectBudgetInfo(params2);
//        handbudgetdate(budgetInfos2,"部门年预算");
//        //组织预算 年
//        List<BudgetInfo> budgetInfos12 = budgetInfoMapper.selectBudgetInfoOrg(params2);
//        handbudgetdate(budgetInfos12,"组织年预算");
//        //部门预算 年研发费用
//        List<BudgetInfo> budgetInfos2yf = budgetInfoMapper.selectBudgetInfo(params2);
//        handbudgetdate(budgetInfos2yf,"部门年预算研发费用");
//        //组织预算 年研发费用
//        List<BudgetInfo> budgetInfos12yf = budgetInfoMapper.selectBudgetInfoOrg(params2);
//        handbudgetdate(budgetInfos12yf,"组织年预算研发费用");
        logger.info("预算信息推送完成");
    }
    /**
     * 预算接口数据整理及接口调用
     * @param budgetInfos
     */
    public void handbudgetdate(List<BudgetInfo> budgetInfos,String discribe){
        //整理数据
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:dd");
        String format = sdf.format(date);
        System.out.println(format);
//        String compid = "SYZLCLY";
//        String account = "RICHFUL";
        //接口名称
        String service = "syncBudgetDrafting";
//        String responseType = "2";
//        String clientip = "";
//        String signType = "MD5";
//        String key = "d597c54a85334f9cb2e49a8b25bc29da";
        String jms = account+format+key;
        String sign= "";
        try {
            // 创建MD5加密对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 执行加密操作
            byte[] messageDigest = md.digest(jms.getBytes());
            // 将字节数组转换为16进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            // 返回加密后的字符串
//            return hexString.toString();
            sign = hexString.toString();
            System.out.println(sign);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }

        JSONObject param = new JSONObject();
        param.put("timestamp",format);
        param.put("compid",compid);
        param.put("account",account);
        param.put("service",service);
        param.put("responseType",responseType);
//        param.put("clientip",clientip);
        param.put("signType",signType);
        param.put("sign",sign);

        JSONArray jsa = new JSONArray();
        for (BudgetInfo budgetInfo : budgetInfos) {
            JSONObject params01 = new JSONObject();
            //法人公司
            params01.put("companyCode",budgetInfo.getPk_orgcode());
            params01.put("profitCode","");
            //部门
            params01.put("budgetDeptCode",budgetInfo.getPk_deptcode());
            params01.put("projectCode","");
            params01.put("wbsCode","");
            params01.put("nbddCode","");
            //预算科目代码
            params01.put("budgetCode",budgetInfo.getPk_measurecode());
            //余额规则
            params01.put("balBalance","0");
            //预算周期1年度预算2月度预算3季度预算
            params01.put("budgetCycle","2");
            //年
            params01.put("year",budgetInfo.getYear());
            //月
            if(!budgetInfo.getMonth().equals("~")){
                params01.put("months",budgetInfo.getMonth());
            }
            //余额
            params01.put("budgetAmountMount",budgetInfo.getMoney());
            jsa.add(params01);
        }
        JSONObject budgetInfo = new JSONObject();
        budgetInfo.put("budgetInfo",jsa);
        param.put("data",budgetInfo);
        //接口调用
        String uuid = IdGen.uuid();
        String sendfkurl2 = sendfkurl+"/syncBudgetDrafting";
        logger.info(uuid+discribe+"请求费控系统预算url: "+sendfkurl2);
        logger.info(uuid+discribe+"请求费控系统预算入参: "+param);
        String s = OkHttpUtils.okHttpPost(sendfkurl2, param.toString());
        logger.info(uuid+discribe+"请求费控系统预算返回参数: "+s);
    }

    @Override
    public void bushRateTofk(String date){
        String date2 = date;
        RateInfo params = new RateInfo();
        Calendar instance = Calendar.getInstance();
        int y = instance.get(Calendar.YEAR);
        int m = instance.get(Calendar.MONTH)+ 1;
        String fm = String.format("%02d", m);
        int i = instance.get(Calendar.DATE);
        String da = String.format("%02d", i);
        if(StringUtils.isNotEmpty(date)){
            StringBuilder stringBuilder = new StringBuilder(date);
            //字符串替换,包含开头索引不包含结束索引
            StringBuilder replace = stringBuilder.replace(8, 11,"01");
            date2 = date.replaceAll("-","");
            params.setRatedate(replace.toString());
        }else{
            date = y + "-" + fm + "-01";
            date2 = y+fm+da;
            params.setRatedate(date);
        }
        List<RateInfo> rateInfos = rateInfoMapper.selectRateInfo(params);
        //数据处理及
        handbushRatedate(rateInfos,date2,"erp日汇率同步费控");
    }
    /**
     * 日汇率接口数据整理及接口调用
     * @param rateInfos
     * @param date
     * @param discribe
     */
    public void handbushRatedate(List<RateInfo> rateInfos,String date, String discribe){
        //整理数据
        Date date2 = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:dd");
        String format = sdf.format(date2);
        System.out.println(format);
        //接口名称
        String service = "syncExchangeRateCommon";
        String jms = account+format+key;
        String sign= "";
        try {
            // 创建MD5加密对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 执行加密操作
            byte[] messageDigest = md.digest(jms.getBytes());
            // 将字节数组转换为16进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            // 返回加密后的字符串
//            return hexString.toString();
            sign = hexString.toString();
            System.out.println(sign);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }

        JSONObject param = new JSONObject();
        param.put("timestamp",format);
        param.put("compid",compid);
        param.put("account",account);
        param.put("service",service);
        param.put("responseType",responseType);
//        param.put("clientip",clientip);
        param.put("signType",signType);
        param.put("sign",sign);

        JSONArray jsa = new JSONArray();
        for (RateInfo rateInfo : rateInfos) {
            JSONObject params01 = new JSONObject();
            //汇率日期 当天日期
            params01.put("conversionDate",date);
            //本币币种编码
            params01.put("toCurrency",rateInfo.getPk_currtypecode());
            //本币币种名称
            params01.put("toCurrencyName",rateInfo.getPk_currtypename());
            //目的币种编码
            params01.put("fromCurrency",rateInfo.getOppcurrtypecode());
            //目的币种名称
            params01.put("fromCurrencyName",rateInfo.getOppcurrtypename());
            //法人公司代码 汇率方案公司代码
            params01.put("companyCode",rateInfo.getPk_exrateschemepk_orgcode());
            //折算方式费控(默认乘法 空或者1-乘法 2-除法) bip 0=源币种×汇率＝目的币种;1=源币种÷汇率＝目的币种;
            String convmode = rateInfo.getConvmode();
            if(StringUtils.isNotBlank(convmode) && "1".equals(convmode)){
                params01.put("conversionMethod","2");
            }else{
                params01.put("conversionMethod","1");
            }

            //汇率值
            if(null != rateInfo.getRate()){
                String s = rateInfo.getRate().toString();
                params01.put("conversionRate",s);
            }
            jsa.add(params01);
        }
        JSONObject budgetInfo = new JSONObject();
        budgetInfo.put("exchangeRateInfo",jsa);
        param.put("data",budgetInfo);
        //接口调用
        String uuid = IdGen.uuid();
        String sendfkurl2 = sendfkurl+"/syncExchangeRateCommon";
        logger.info(uuid+discribe+"请求费控系统日汇率url: "+sendfkurl2);
        logger.info(uuid+discribe+"请求费控系统日汇率入参: "+param);
        String s = OkHttpUtils.okHttpPost(sendfkurl2, param.toString());
        logger.info(uuid+discribe+"请求费控系统日汇率返回参数: "+s);
    }

    public AjaxResult huidiao(String req, HttpServletRequest request){
//        PrivateAppCrypto
        return null;
    }

    @Override
    public void upbillpaystatus(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //查询统一支付结算近来一个月数据,根据结算状态查询资金付款单中未结算的单据 根据未结算单据设置状态
        logger.info("统一支付状态同步资金付款单开始");
        Paybill paybill = new Paybill();
        paybill.setEndDate(sdf.format(new Date()));
        Calendar instance = Calendar.getInstance();
        instance.set(Calendar.MONTH,-3);
        paybill.setStartDate(sdf.format(instance.getTime()));
        List<Paybill> paybills = paybillMapper.selectPaybill(paybill);
        List<String> list = new ArrayList<>();
        for (Paybill paybill1 : paybills) {
            list.add(paybill1.getPaybillid());
        }
        if(!list.isEmpty()){
            int i = paybillMapper.updatePaybillStatus(list);
        }
        logger.info("统一支付状态同步资金付款单结束");

    }

    /**
     *  erp推送付款合同到费控平台
     */
    @Override
    public void pushPayCon(){
        String uuid = IdGen.uuid();
        //请求数据整理
        PayConH param = new PayConH();
        Calendar instance = Calendar.getInstance();
        instance.set(Calendar.MONTH,-3);
        Date time = instance.getTime();
        Date date = new Date();
        SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd");
        String formate = spf.format(date);
        String formats = spf.format(time);
        param.setStartDate(formats);
        param.setEndDate(formate);
        //查询出需要推送的并且状态为未推送的
        List<PayConH> payConHS = payConMapper.selectPayConlist(param);

        if(!payConHS.isEmpty()){
            for (PayConH payConH : payConHS) {
                JSONObject jparam = new JSONObject();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id",payConH.getId());
                //合同编码
                jsonObject.put("htbh",payConH.getCode());
                //企业编码
                jsonObject.put("qybh","RICHFUL");
                //合同名称
                jsonObject.put("htmc",payConH.getName());
                //操作类型 新增 版本号为空则新增否则为更新0更新 1新增 2 删除；3部分更新
                if(StringUtils.isNotBlank(payConH.getPushfkv()) && !"~".equals(payConH.getPushfkv())){
                    jsonObject.put("czlx","0");
                }else {
                    jsonObject.put("czlx","1");
                }
                //是否敞口合同0否-1是
                //总价合同/框架合同
                if(StringUtils.isNotBlank(payConH.getOpenct()) && "Y".equals(payConH.getOpenct())){
                    jsonObject.put("sfckht","1");
                    jsonObject.put("fkxs","4");
                }else{
                    jsonObject.put("sfckht","0");
                    jsonObject.put("fkxs","1");
                }
                //合同金额
                jsonObject.put("htje",payConH.getNtotaltaxmny());
                //本币合同金额
                jsonObject.put("bbhtje",payConH.getNtotaltaxmny());
                //签订日期
                jsonObject.put("qdrq",payConH.getSubsdate());
                //生效日期
                jsonObject.put("sxrq",payConH.getValdate());
                //终止日期
                jsonObject.put("zzrq",payConH.getInvallidate());
                //币种
                jsonObject.put("bz",payConH.getCoricode());
//                jsonObject.put("hl",payConH.getNexchangerate());
                //制单人编码
                jsonObject.put("wfdsrgh",payConH.getUsercode());
                //合同状态
                jsonObject.put("htzt","3");
                //合同等级
                jsonObject.put("contractLevelName",payConH.getHtdj());
                //项目名称
                jsonObject.put("xmmc",payConH.getProject_name());
                //付款银行名称
                jsonObject.put("payBankAccoName",payConH.getPayaccname());
                //付款开户银行
                jsonObject.put("payAccoOpenBank",payConH.getPayopname());
                //付款银行账号
                jsonObject.put("payBankAccount",payConH.getPayaccnum());
                //部门
                jsonObject.put("wfdsrbmqc",payConH.getDeptname());
                //是否招投标
                if(StringUtils.isNotBlank(payConH.getSfztb()) && "Y".equals(payConH.getSfztb())){
                    jsonObject.put("sfztb","1");
                }else{
                    jsonObject.put("sfztb","0");
                }
                String billtypcode = payConH.getBilltypcode();
                if("FCT1-Cxx-02".equals(billtypcode)){
                    //合同类别编码
                    jsonObject.put("htlbbh","FWCGHT");
                    //合同类别名称
                    jsonObject.put("htlbmc","服务采购合同");
                }else if("FCT1-Cxx-03".equals(billtypcode)){
                    //合同类别编码
                    jsonObject.put("htlbbh","ZLHT_YZLB");
                    //合同类别名称
                    jsonObject.put("htlbmc","租赁合同");
                }else if("FCT1-Cxx-04".equals(billtypcode)){
                    //合同类别编码
                    jsonObject.put("htlbbh","Property");
                    //合同类别名称
                    jsonObject.put("htlbmc","技术合同");
                }else if("FCT1-Cxx-06".equals(billtypcode)){
                    //合同类别编码
                    jsonObject.put("htlbbh","Xsht");
                    //合同类别名称
                    jsonObject.put("htlbmc","设备采购合同");
                }else if("FCT1-Cxx-01".equals(billtypcode) ){
                    logger.info(uuid+"/"+payConH.getId()+"/"+payConH.getCode()+"建设工程付款合同已过滤");
                    continue;
                }else if("FCT1-Cxx-05".equals(billtypcode)){
                    logger.info(uuid+"/"+payConH.getId()+"/"+payConH.getCode()+"委托加工付款合同已过滤");
                    continue;
                }
                jparam.put("contractsSyncBean",jsonObject);
                List<PayConB> payConBList = payConH.getPayConBList();
                List<PayConC> payConCList = payConH.getPayConCList();
                JSONArray jsar = new JSONArray();
                JSONArray fkjhList = new JSONArray();
                JSONObject jso = new JSONObject();
                if(StringUtils.isBlank(payConH.getOpenct()) || !"Y".equals(payConH.getOpenct())){
                    //供应商原币金额
                    jso.put("htje",payConH.getNtotalorigmny());
                    //供应商本币金额
                    jso.put("bbhtje",payConH.getNtotaltaxmny());
                }
                jso.put("gysmc",payConH.getSkfname());
                jso.put("gysbh",payConH.getSkfcode());
                jso.put("lxrmc",payConH.getLinkname());
                jso.put("lxdh",payConH.getLinkcell());
                jso.put("yhzh",payConH.getPayeaccnum());
                if(StringUtils.isNotEmpty(payConH.getBeizhu()) && !"~".equals(payConH.getBeizhu())) jso.put("fksm",payConH.getBeizhu());
                for (PayConC payConC : payConCList) {
                    JSONObject fkjhjso = new JSONObject();
                    //付款计划比例1为100%
                    String planrate = payConC.getPlanrate();
                    if(StringUtils.isNotBlank(planrate)){
                        BigDecimal bigDecimal = new BigDecimal(planrate);
                        BigDecimal divide = bigDecimal.divide(new BigDecimal("100"));
                        fkjhjso.put("fkbl",divide.toString());
                    }
                    if(StringUtils.isBlank(payConH.getOpenct()) || !"Y".equals(payConH.getOpenct())){
                        //付款金额
                        fkjhjso.put("fkje",payConC.getPlanmoney());
                    }
                    fkjhjso.put("fkrq",payConC.getPlenddate());
                    //合同阶段名称
                    fkjhjso.put("htjdmc",payConC.getAccountnum());
                    fkjhjso.put("fktj","合同生效");
                    fkjhjso.put("fkfsmc",payConH.getJsfsname());
                    fkjhList.add(fkjhjso);
                }
                jso.put("fkjhList",fkjhList);
                jsar.add(jso);
                jparam.put("supplierList",jsar);

                //接口调用
                //接口名称测试
                String service = "FCCONTRACT_OUTAPI_Contract";
                String sendfkurl2 = "/fcopen/fcoutapi";
                String discribe = "请求费控付款合同";
                discribe = discribe + payConH.getId();
                JSONObject pushtofk = pushtofk(uuid,sendfkurl2, service, discribe, jparam);
//                JSONObject pushtofk = new JSONObject();
                String status = pushtofk.optString("status");
                //处理结果
                if("200".equals(status)){
                    PayConH payConH1 = new PayConH();
                    payConH1.setId(payConH.getId());
                    payConH1.setPushfk("Y");
                    payConH1.setPushfkv(payConH.getVersion());
                    int i = payConMapper.updatePayCon(payConH1);
                    if(i > 0){
                        logger.info(uuid+"/"+payConH.getId()+"/"+payConH.getCode()+"付款合同状态已更改");
                    }
                }
            }
        }
    }


    /**
     *  请求费控接口工具类
     * @param sendurl
     * @param service
     * @param discribe
     * @param dparam
     * @return
     */
    public JSONObject pushtofk(String uuid,String sendurl, String service,String discribe,JSONObject dparam){
        //生成sign
        Date date = new Date();
        SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formate = spf.format(date);
        String jms = account+formate+key;
        String sign= "";
        try {
            // 创建MD5加密对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 执行加密操作
            byte[] messageDigest = md.digest(jms.getBytes());
            // 将字节数组转换为16进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            // 返回加密后的字符串
//            return hexString.toString();
            sign = hexString.toString();
            System.out.println(sign);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        JSONObject param = new JSONObject();
        param.put("timestamp",formate);
        param.put("compid",compid);
        param.put("account",account);
        param.put("service",service);
        param.put("responseType",responseType);
//        param.put("clientip",clientip);
        param.put("signType",signType);
        param.put("sign",sign);
        param.put("data",dparam);
        String sendurlt = sendfkurl+sendurl;
        logger.info(uuid+discribe+"url"+sendurlt);
        logger.info(uuid+discribe+"入参"+param);
        String s = OkHttpUtils.okHttpPost(sendurlt,param.toString());
        logger.info(uuid+discribe+"返回参数"+s);
        JSONObject jsonObject1 = JSONObject.fromObject(s);
        return jsonObject1;
    }



}
